import backtrader as bt

class BuyAndHoldStrategy(bt.Strategy):
    """
    一个简单的买入并持有策略，作为基准。
    在回测的第一天买入，并一直持有到结束。
    """
    def __init__(self):
        self.log('Buy and Hold Strategy Initialized')
        # 跟踪我们是否已经买入
        self.bought = False

    def log(self, txt, dt=None):
        dt = dt or self.datas[0].datetime.date(0)
        print(f'{dt.isoformat()}, {txt}')

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            return
        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(f'BUY EXECUTED, Price: {order.executed.price:.2f}')
            elif order.issell():
                self.log(f'SELL EXECUTED, Price: {order.executed.price:.2f}')
        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')

    def next(self):
        # 仅在第一根K线上执行一次买入操作
        if not self.bought:
            # 获取当前所有可以用的现金，计算可以买多少股
            size = int(self.broker.getcash() / self.data.close[0])
            self.log(f'BUY CREATE, Size: {size}, Close: {self.data.close[0]:.2f}')
            self.buy(size=size)
            self.bought = True 